package com.wing.qualityTesting.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.Idempotent;
import com.wing.productionPlan.model.entity.ProductionWorkOrder;
import com.wing.productionPlan.model.response.ProductionPlanVO;
import com.wing.productionPlan.model.response.ProductionWorkOrderVO;
import com.wing.productionPlan.service.ProductionWorkOrderService;
import com.wing.qualityTesting.model.entity.QualityTestingRecord;
import com.wing.qualityTesting.model.response.WorkOrderQualityTestingTaskVO;
import com.wing.qualityTesting.service.QualityTestingRecordService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.qualityTesting.model.entity.WorkOrderQualityTestingTask;
import com.wing.qualityTesting.model.request.WorkOrderQualityTestingTaskForm;
import com.wing.qualityTesting.service.WorkOrderQualityTestingTaskService;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-开工单质检任务表管理", tags = "#/qualityTesting/workOrderQualityTestingTask")
@RestController("workOrderQualityTestingTaskController")
@RequestMapping("qualityTesting/admin/workOrderQualityTestingTask")
@RequiredArgsConstructor
public class WorkOrderQualityTestingTaskController {

    private final WorkOrderQualityTestingTaskService workOrderQualityTestingTaskService;
    private final QualityTestingRecordService qualityTestingRecordService;
    private final ProductionWorkOrderService productionWorkOrderService;


    @ApiOperation(value = "查询所有开工单质检任务表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "processId", value="工序id", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "workOrderCode", value="工单编号", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "code", value="质检任务编号", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "status", value="状态:inspect(0,送检中);finish(1,完成)", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<WorkOrderQualityTestingTaskVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long processId
            ,String workOrderCode
            ,String code
            ,WorkOrderQualityTestingTask.Status status

    ){

        Page<WorkOrderQualityTestingTask> pg = new Page<>(page, limit);
        Map paramMap = new HashMap();
        if(processId != null){
            paramMap.put("processId",processId);
        }
        if(StringUtils.isNotBlank(workOrderCode)){
            paramMap.put("workOrderCode",workOrderCode);
        }
        if(StringUtils.isNotBlank(code)){
            paramMap.put("code",code);
        }
        if(status != null){
            paramMap.put("status",status.getValue());
        }
        paramMap.put("enterpriseCode", JwtUtils.getEnterpriseCode());
        //搜索
        IPage<WorkOrderQualityTestingTaskVO> list = workOrderQualityTestingTaskService.pageList4app(pg,paramMap);
        for(WorkOrderQualityTestingTaskVO item : list.getRecords()){
            if(item.getCreator().equals(JwtUtils.getLoginUserId())){
                item.setWhetherEdit(0);
            }

        }
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加开工单质检任务表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    @Idempotent(keyPrefix = "workOrderQualityTestingTaskAdd")

    public JsonResult add(@Validated(WorkOrderQualityTestingTaskForm.Add.class) WorkOrderQualityTestingTaskForm workOrderQualityTestingTaskForm) {
        String status = "2";
        int add = workOrderQualityTestingTaskService.add(workOrderQualityTestingTaskForm, status);
        if ( add > 0) {
            if (add == 2) {
                return JsonResult.fail("添加失败 送检数不能大于剩余可送检数!");
            }
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "修改开工单质检任务表", notes = "修改")
    @PutMapping("/update")
    @Idempotent(keyPrefix = "workOrderQualityTestingTaskUpdate")
    public JsonResult update(@Validated(WorkOrderQualityTestingTaskForm.Update.class) WorkOrderQualityTestingTaskForm workOrderQualityTestingTaskForm) {
        WorkOrderQualityTestingTask workOrderQualityTestingTask = workOrderQualityTestingTaskService.getById(workOrderQualityTestingTaskForm.getId());
        if(workOrderQualityTestingTask == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(WorkOrderQualityTestingTask.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(workOrderQualityTestingTaskForm, workOrderQualityTestingTask, copyOptions);
        //关闭要判断是否有质检记录
        if(workOrderQualityTestingTask.getStatus().getValue() == 3){
            QualityTestingRecord testingRecord = qualityTestingRecordService.getOne(new LambdaQueryWrapper<QualityTestingRecord>().eq(QualityTestingRecord::getQualityTestingTaskId
                    , workOrderQualityTestingTask.getId()));
            if(testingRecord != null){
                return JsonResult.fail("已存在质检记录，不能关闭！");
            }
        }

        if (workOrderQualityTestingTaskService.updateById(workOrderQualityTestingTask)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除开工单质检任务表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "workOrderQualityTestingTaskId", value = "开工单质检任务表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long workOrderQualityTestingTaskId) {
        if (workOrderQualityTestingTaskService.removeById(workOrderQualityTestingTaskId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "查询开工单信息", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "workOrderId", value="工单id", dataType = "Long", paramType = "query")
    })
    @GetMapping("/getWorkOrderInfoById")
    public JsonResult<ProductionWorkOrderVO> getWorkOrderInfoById(Long workOrderId,String workOrderCode){
        ProductionWorkOrderVO workOrderVO = productionWorkOrderService.get4appById(workOrderId,workOrderCode);
        return JsonResult.success(workOrderVO);
    }

    @ApiOperation(value = "打印标签", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "workOrderId", value="任务id", dataType = "Long", paramType = "query")
    })
    @GetMapping("/printLabels")
    public JsonResult printLabels(Long id){
        try {
            workOrderQualityTestingTaskService.printLabels(id);
            return JsonResult.success("操作成功");
        }catch (Exception e){
            log.error("printLabels接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }
}
